package cn.com.dhc.danlu.widget;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

import cn.com.dhc.danlu.R;

/**
 * User: Geek_Soledad(wuhaiyang@danlu.com) Date: 2016-07-20 Time: 10:02
 * Description: .....
 */
public class SlideButton extends View {

    /**
     * 代表 向右滑动校验 | 验证成功 背景
     */
    private Bitmap mBackgroudBitmap;

    /**
     * 可以滑动的图片
     */
    private Bitmap mSlideBitmap;
    private Paint mPaint;

    /**
     * 滑动按钮的左边届
     */
    private float slideBtn_left;

    /**
     * 移动阈值
     */
    private int threshold;

    private float mScaleValue;
    /**
     * down 事件时的x值
     */
    private int firstX;
    /**
     * touch 事件的上一个x值
     */
    private int lastX;
    private boolean isUp = false;
    /**
     * 标识当前用户是否校验完成
     */
    private boolean isValidateSuc = false;
    private boolean canHidden = false;
    private boolean isFirstScale = false;
    private boolean mCurrentState = false;
    private OnSlideListener mListener;

    public SlideButton(Context context) {
        this(context, null);
    }

    public SlideButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }


    public SlideButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initApi();
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void initApi() {
        // 初始化图片
        mBackgroudBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_slide_wait_bg);
        int w = mBackgroudBitmap.getWidth();
        mSlideBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_slidebar);
        //		mBackgroudBitmap = magnifyBitmap(mBackgroudBitmap,1.5f, 1.23f);
        // 1.23 = 80 / 65
        estimate(w);
        mSlideBitmap = magnifyBitmap(mSlideBitmap, 1.23f, 1.23f);


        mBackgroudBitmap = magnifyBitmap(mBackgroudBitmap, mScaleValue, 1.23f);

        // 初始化 画笔
        mPaint = new Paint();
        mPaint.setAntiAlias(true); // 打开抗矩齿
        threshold = mBackgroudBitmap.getWidth() / 2;
    }

    /**
     * 计算一个预估值
     */
    public void estimate(int oriWidth) {
        Log.w("TAG", "screenWidth = " + getScreenWidth());
        float dialogFragWidth = (float) (getScreenWidth() * 0.85);
        Log.w("TAG", "dialogFragWidth = " + dialogFragWidth);
        float slideWidth = dialogFragWidth - dip2px(getContext(), 115);
        Log.w("TAG", "slideWidth = " + slideWidth);
        if (slideWidth > oriWidth) {
            mScaleValue = slideWidth / oriWidth;
        } else {
            mScaleValue = oriWidth / slideWidth;
        }
        Log.w("TAG", "mScaleValue = " + mScaleValue);
    }

    private Bitmap magnifyBitmap(Bitmap bitmap, float sx, float sy) {
        Matrix matrix = new Matrix();
        matrix.postScale(sx, sy); // 长和宽放大缩小的比例
        return Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    }

    public float getScreenWidth() {
        WindowManager windowManager = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        return display.getWidth();
    }

    public void setThreshold(int threshold) {
        this.threshold = threshold;
    }

    public boolean isValidateSuc() {
        return isValidateSuc;
    }

    public void setIsValidateSuc(boolean isValidateSuc) {
        this.isValidateSuc = isValidateSuc;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (isValidateSuc) {
            return true;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isUp = false;
                firstX = lastX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                isUp = false;
                // 计算 手指在屏幕上移动的距离
                int dis = (int) (event.getX() - lastX);

                // 将本次的位置 设置给lastX
                lastX = (int) event.getX();

                // 根据手指移动的距离，改变slideBtn_left 的值
                slideBtn_left = slideBtn_left + dis;
                flushView();
                break;
            case MotionEvent.ACTION_UP:
                // 在发生拖动的情况下，根据最后的位置，判断当前开关的状态
                int maxLeft = mBackgroudBitmap.getWidth() - mSlideBitmap.getWidth(); // slideBtn
                // 左边届最大值
            /*
             * 根据 slideBtn_left 判断，当前应是什么状态
			 */
                // 此时应为 打开的状态
                mCurrentState = slideBtn_left >= maxLeft - 10;
                isUp = true;
                canHidden = true;
                flushState();
                break;
        }
        return true;
    }

    private void flushView() {
        /*
         * 对 slideBtn_left 的值进行判断 ，确保其在合理的位置 即 0<=slideBtn_left <= maxLeft
		 */
        int maxLeft = mBackgroudBitmap.getWidth() - mSlideBitmap.getWidth(); // slideBtn
        // 左边届最大值
        // 确保 slideBtn_left >= 0
        slideBtn_left = (slideBtn_left > 0) ? slideBtn_left : 0;
        // 确保 slideBtn_left <=maxLeft
        slideBtn_left = (slideBtn_left < maxLeft) ? slideBtn_left : maxLeft;

		/*
		 * 刷新当前视图 导致 执行onDraw执行
		 */
        if (slideBtn_left > threshold) {
            if (slideBtn_left > threshold && slideBtn_left < maxLeft && isUp) {
                animateValue(300, (int) slideBtn_left, 0);
            } else {
                invalidate();
            }
        } else {
            if (isUp) {
                animateValue(150, (int) slideBtn_left, 0);
            } else {
                invalidate();
            }
        }
    }

    private void flushState() {
        if (mCurrentState) {
            mBackgroudBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_slide_suc_bg);
            mBackgroudBitmap = magnifyBitmap(mBackgroudBitmap, mScaleValue, 1.23f);
            slideBtn_left = mBackgroudBitmap.getWidth() - mSlideBitmap.getWidth();
            isValidateSuc = true;
            if (null != mListener) {
                mListener.onSlideState(true);
            }
        } else {
            mBackgroudBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.icon_slide_wait_bg);
            mBackgroudBitmap = magnifyBitmap(mBackgroudBitmap, mScaleValue, 1.23f);
        }
        flushView();
    }

    private void animateValue(int duration, int fromValue, int toValue) {
        ValueAnimator animator = ValueAnimator.ofInt(fromValue, toValue).setDuration(duration);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                slideBtn_left = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        animator.start();
    }

    @SuppressLint("DrawAllocation")
    @Override
    protected void onDraw(Canvas canvas) {
        // super.onDraw(canvas);
        // 绘制 背景
		/*
		 * backgroundBitmap 要绘制的图片 left 图片的左边届 top 图片的上边届 paint 绘制图片要使用的画笔
		 */
        if (null == mBackgroudBitmap) {
            return;
        }
        canvas.drawBitmap(mBackgroudBitmap, 0, 0, mPaint);
        if (slideBtn_left > 0) {
            Paint paint = new Paint();
            paint.setColor(getResources().getColor(R.color.color_13cf85));
            paint.setAntiAlias(true);
            int maxLeft = mBackgroudBitmap.getWidth() - mSlideBitmap.getWidth(); // slideBtn
            if (slideBtn_left == maxLeft && canHidden) {
                paint.setColor(Color.TRANSPARENT);
            }
            RectF rectF = new RectF(0, 0, slideBtn_left + mSlideBitmap.getWidth(), dip2px(getContext(), 40));
            canvas.drawRoundRect(rectF, dip2px(getContext(), 20), dip2px(getContext(), 20), paint);
        }
        // 绘制 可滑动的按钮
        canvas.drawBitmap(mSlideBitmap, slideBtn_left, 0, mPaint);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /**
         * 设置当前view的大小 width :view的宽度 height :view的高度 （单位：像素）
         */
        if (null == mBackgroudBitmap) {
            initApi();
        }
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);

        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        //指定宽度
        setMeasuredDimension(widthSize, dip2px(getContext(), 40));
        //		mScaleValue = (float) (widthSize * 1.0) / mBackgroudBitmap.getWidth();
        //多次连续调用
    }

    public void setSlideListener(OnSlideListener listener) {
        this.mListener = listener;
    }

    public interface OnSlideListener {
        void onSlideState(boolean isSlideOver);
    }

}
